import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings


def ListTreeFindByKey(items, key):
    for i in items:
        if i['key'] == key:
            return i
        elif len(i["children"]) > 0:
            r = ListTreeFindByKey(i["children"], key)
            if r:return r

    return None


class TimeStructListResource(BaseResource):
    def get(self, calendar_enum):
        ts = models.TimeStruct.get_by_calendar_enum(calendar_enum,self.current_org)

        rs = []
        for t in ts:
            r = t.to_tree()
            if r['parent_id'] == 0:
                rs.append(r)
            else:
                s = ListTreeFindByKey(rs,r['parent_id'])
                s['children'].append(r)    

        return rs

    @require_admin_default
    def post(self, calendar_enum):
        req = request.get_json(force=True)

        timestruct = models.TimeStruct(
            calendar_enum = calendar_enum,
            org=self.current_org,
            title = req["title"],
            timeserialnode_enum = req["timeserialnode_enum"],
            num = req["num"],
            parent_id = req["parent_id"],
        )

        try:
            models.db.session.add(timestruct)
            models.db.session.commit()
        except IntegrityError as e:
            if "title" in str(e):
                abort(400, message="名称已存在.")
            abort(500)

        self.record_event(
            {"action": "create", "object_id": timestruct.id, "object_type": "timestruct"}
        )


class TimeStructResource(BaseResource):
    def get(self, id):
        timestruct = models.TimeStruct.get_by_parent_id(id,self.current_org)
        return [t.to_dict() for t in timestruct]

    @require_admin_default
    def delete(self, id):
        models.TimeStruct.delete_by_id(id)

        try:
            models.db.session.commit()
        except IntegrityError as e:
            abort(500, message=str(e))

        self.record_event(
            {"action": "delete", "object_id": id, "object_type": "timestruct"}
        )